<!-- eslint-disable vue/valid-v-slot -->
<template>
  <div class="main-container all-box">
    <div class="box-left">
      <a-input
        style="width: 100%"
        v-model="form.name"
        allow-clear
        placeholder="请输入商品名称"
        @change="doRefresh(1)"
      />
      <div class="tong">我的通用库存：{{ generalInventory }}</div>
      <a-table
        style="margin-top: 20px"
        :loading="tables.tableLoading"
        :data="table.dataList"
        :pagination="false"
        :column-resizable="true"
        :rowKey="rowKey"
        table-layout-fixed
        @row-click="handleRowClick"
      >
        <template #columns>
          <a-table-column
            v-for="item of userTableList"
            :key="item.key"
            align="left"
            :width="item.width"
            :title="(item.title as string)"
            :data-index="(item.key as string)"
            :ellipsis="true"
            :tooltip="true"
          >
            <template v-if="item.key === 'mallMallStock'" #cell="{ record }">
              {{ record.stock }}
            </template>
          </a-table-column>
        </template>
      </a-table>
      <TableFooter :pagination="pagination" position="center" />
    </div>
    <div class="box-right">
      <div class="top-but">
        <div class="top-left" v-if="putList.length <= 0">
          <span style="color: #3491fa; margin-right: 20px; font-size: 13px">下单详情</span>
          <span style="margin-right: 20px; font-size: 13px">下单数量：0个</span>
          <span style="margin-right: 20px; font-size: 13px">发货数量：0个</span>
          <span style="margin-right: 20px; font-size: 13px">下单金额：0元</span>
          <span style="margin-right: 20px; font-size: 13px">快递费：0元</span>
          <span style="margin-right: 20px; font-size: 13px">总金额：0元</span>
        </div>
        <div class="top-left" v-else>
          <span style="color: #3491fa; margin-right: 20px; font-size: 13px">下单详情</span>
          <span style="margin-right: 20px; font-size: 13px">下单数量：{{ totalNumberTop }}个</span>
          <span style="margin-right: 20px; font-size: 13px">发货数量：{{ putList.length }}个</span>
          <span style="margin-right: 20px; font-size: 13px">下单金额：{{ totalPriceTop }}元</span>
          <span style="margin-right: 20px; font-size: 13px">快递费：{{ totalFeeTop }}元</span>
          <span style="margin-right: 20px; font-size: 13px">总金额：{{ totalTop }}元</span>
        </div>
        <a-button type="primary" @click="openPay"> 立即下单 </a-button>
      </div>
      <div class="all-table">
        <a-table
          style="margin-top: 20px"
          :data="allGoodList"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          table-layout-fixed
        >
          <template #columns>
            <a-table-column
              v-for="item of allGoodColumns"
              :key="item.key"
              align="left"
              :width="item.width"
              :title="(item.title as string)"
              :data-index="(item.key as string)"
              :ellipsis="true"
              :tooltip="true"
            >
              <template v-if="item.key === 'mallMallStock'" #cell="{ record }">
                {{ record.stock }}
              </template>
              <template v-if="item.key === 'cost'" #cell="{ record }">
                {{ record.cost }}
              </template>
              <template v-if="item.key === 'number'" #cell="{ record }">
                {{ record.number }}
              </template>
              <template v-if="item.key === 'allPrice'" #cell="{ record }">
                {{ Math.floor(record.cost * record.number * 100) / 100 }}
              </template>
              <template v-if="item.key === 'action'" #cell="{ record }">
                <a-button class="list-button" type="text" size="small" @click="delGoodFn(record)"
                  >删除</a-button
                >
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
      <div class="putTitle">
        收货详情
        <a-button class="list-button" type="text" size="small" @click="openUpdate"
          >新增</a-button
        ></div
      >
      <div class="putList">
        <div class="item" v-for="(item, index) in putList" :key="item.id">
          <div class="item-top">
            <div class="item-text"
              >收货信息：{{ item.expressName }} {{ item.expressPhone }} {{ item.address
              }}{{ item.expressAddress }} 备注：{{ item.placeOrderRemarks }}
            </div>
            <div class="item-but">
              <a-button
                class="list-button"
                type="text"
                size="small"
                status="success"
                @click="openUpdate(item)"
                >编辑</a-button
              >
              <a-button
                class="list-button"
                type="text"
                size="small"
                status="danger"
                @click="delPutFn(item)"
                >删除</a-button
              >
            </div>
          </div>
          <a-table
            style="margin-top: 20px"
            :data="item.mallOrderItems"
            :pagination="false"
            :column-resizable="true"
            :rowKey="rowKey"
            table-layout-fixed
          >
            <template #columns>
              <a-table-column
                v-for="items of putGoodColumns"
                :key="items.key"
                align="left"
                :width="items.width"
                :title="(items.title as string)"
                :data-index="(items.key as string)"
                :ellipsis="true"
                :tooltip="true"
              >
                <template v-if="items.key === 'mallMallStock'" #cell="{ record }">
                  {{ record.stock }}
                </template>
                <template v-if="items.key === 'cost'" #cell="{ record }">
                  {{ record.cost }}
                </template>
                <template v-if="items.key === 'number'" #cell="{ record }">
                  <a-input-number
                    v-model="record.number"
                    placeholder="Please Enter"
                    class="input-demo"
                    :min="0"
                    @focus="numberFn(index)"
                    @blur="updateTotal()"
                  />
                </template>
                <template v-if="items.key === 'allPrice'" #cell="{ record }">
                  {{ Math.floor(record.cost * record.number * 100) / 100 }}
                </template>
              </a-table-column>
            </template>
          </a-table>
          <div
            style="
              border: 1px solid rgba(229, 231, 235, var(--tw-border-opacity));
              border-top: 0;
              padding: 12px;
              text-align: left;
            "
            >统计：商品成本:{{ Math.floor(item.totalCost * 100) / 100 }}元
            <span style="margin-left: 10px"
              >下单数量:{{ Math.floor(item.totalNumber * 100) / 100 }}个</span
            >
            <span style="margin-left: 10px"
              >下单金额:{{ Math.floor(item.totalPrice * 100) / 100 }}元</span
            >
            <span style="margin-left: 10px"
              >快递费用:{{ Math.floor(item.expressFee * 100) / 100 }}元</span
            >
            <span style="margin-left: 10px"
              >总金额: {{ Math.floor(item.total * 100) / 100 }}元</span
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 商品下单 -->
    <a-modal
      v-model:visible="updateVisible"
      title="商品下单"
      width="500px"
      :mask-closable="false"
      @before-close="beforeCloseUpdate"
      title-align="start"
    >
      <div>注意事项</div>
      <div style="margin-bottom: 20px; background-color: #f7f8fa; padding: 5px">
        1：同一个收件信息内发货多个商品，如果有一个商品或多个商品存在
        快递费，会取新增商品内快递费最高的作为快递费
      </div>
      <a-form ref="updateRef" :auto-label-width="true" :model="updateForm">
        <a-form-item label="发货信息" field="str">
          <a-input hide-button v-model="updateForm.str" placeholder="请输入发货信息">
            <template #append>
              <span
                @click="intellectIdentifyFn"
                style="color: cornflowerblue; padding: 5px; cursor: pointer"
                >智能识别</span
              >
            </template>
          </a-input>
          <template #extra>
            <div>智能识别地址后，请自行核实信息是否正确</div>
          </template>
        </a-form-item>
        <a-form-item label="寄件人" field="senderId">
          <a-select
            v-model="updateForm.senderId"
            style="width: 100%"
            placeholder="请选择寄件人模板"
            allow-clear
          >
            <a-option v-for="item in sendUserList" :key="item.id" :value="item.id">{{
              item.tempName
            }}</a-option>
          </a-select>
        </a-form-item>
        <a-divider dashed>收货信息</a-divider>
        <a-form-item label="划分客户" field="divideUserId">
          <a-select
            v-model="updateForm.divideUserId"
            placeholder="请选择客户"
            :max-tag-count="1"
            allow-clear
            allow-search
            :options="userLists"
            :virtual-list-props="{ height: 200 }"
          />
        </a-form-item>
        <a-form-item
          label="姓名"
          field="expressName"
          :rules="[{ required: true, message: '姓名不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input hide-button v-model="updateForm.expressName" placeholder="请输入姓名" />
        </a-form-item>
        <a-form-item
          label="手机号码"
          field="expressPhone"
          :rules="[{ required: true, message: '手机号码不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input hide-button v-model="updateForm.expressPhone" placeholder="请输入手机号码" />
        </a-form-item>
        <a-form-item
          v-if="updateForm.idState"
          label="身份证号"
          field="expressIdCard"
          :rules="[{ required: true, message: '身份证号不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input hide-button v-model="updateForm.expressIdCard" placeholder="请输入身份证号" />
        </a-form-item>
        <a-form-item v-if="updateForm.idCardImg == true" label="身份证人像面" field="photoFullFace">
          <a-upload
            action="/app/user/mall/file/upload/private"
            :show-file-list="false"
            @success="onCardSuccess1"
            @error="onError"
            :image-preview="true"
          >
            <template #upload-button>
              <div
                class="arco-upload-list-picture custom-upload-avatar"
                v-if="updateForm.photoFullFace"
              >
                <img :src="updateForm.photoFullFaces" />
                <div class="arco-upload-list-picture-mask">
                  <IconEdit />
                </div>
              </div>
              <div class="arco-upload-picture-card" v-else>
                <div class="arco-upload-picture-card-text">
                  <IconPlus />
                </div>
              </div>
              <!-- </div> -->
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item
          v-if="updateForm.idCardImg == true"
          label="身份证国徽面"
          field="photoReverseSide"
        >
          <a-upload
            action="/app/user/mall/file/upload/private"
            :show-file-list="false"
            @success="onCardSuccess2"
            @error="onError"
            :image-preview="true"
          >
            <template #upload-button>
              <div
                class="arco-upload-list-picture custom-upload-avatar"
                v-if="updateForm.photoReverseSide"
              >
                <img :src="updateForm.photoReverseSides" />
                <div class="arco-upload-list-picture-mask">
                  <IconEdit />
                </div>
              </div>
              <div class="arco-upload-picture-card" v-else>
                <div class="arco-upload-picture-card-text">
                  <IconPlus />
                </div>
              </div>
              <!-- </div> -->
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item v-if="updateForm.idCardImg == true" label="免冠照" field="photoBareheaded">
          <a-upload
            action="/app/user/mall/file/upload/private"
            :show-file-list="false"
            @success="onCardSuccess3"
            @error="onError"
            :image-preview="true"
          >
            <template #upload-button>
              <div
                class="arco-upload-list-picture custom-upload-avatar"
                v-if="updateForm.photoBareheaded"
              >
                <img :src="updateForm.photoBareheadeds" />
                <div class="arco-upload-list-picture-mask">
                  <IconEdit />
                </div>
              </div>
              <div class="arco-upload-picture-card" v-else>
                <div class="arco-upload-picture-card-text">
                  <IconPlus />
                </div>
              </div>
              <!-- </div> -->
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item
          label="地区"
          field="regionalCode"
          :rules="[{ required: true, message: '地区不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-cascader
            v-model="updateForm.regionalCode"
            :options="districtsList"
            :field-names="fieldNames"
            placeholder="请输入地区"
            @change="changeCode"
          />
        </a-form-item>
        <a-form-item
          label="详细地址"
          field="expressAddress"
          :rules="[{ required: true, message: '详细地址不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input hide-button v-model="updateForm.expressAddress" placeholder="请输入详细地址" />
        </a-form-item>
        <a-form-item label="备注" field="userRemarks">
          <a-input hide-button v-model="updateForm.userRemarks" placeholder="请输入备注" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="beforeCloseUpdate">取消</a-button>
          <a-button type="primary" @click="confirmUpdate">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <!-- 支付扫码 -->
    <a-modal
      v-model:visible="visibleX"
      :title="path.length > 1 ? '扫码登录' : '扫码支付'"
      width="280px"
      :mask-closable="false"
      title-align="start"
      hide-cancel
      hide-ok
      :before-close="beforCloseX"
    >
      <div>
        <!-- <div v-if="path.length < 1" style="text-align: center">
          ￥<span style="font-size: 26px">{{ detailForm.name }}</span>
        </div> -->
        <img style="width: 240px; height: 240px" :src="imgUrl" alt="" />
      </div>
      <template #footer>
        <a-space>
          <a-button
            type="primary"
            v-if="path.length > 1"
            :loading="loadings"
            @click="paySuccessFnX"
          >
            我已登录
          </a-button>
        </a-space>
      </template>
    </a-modal>
    <!-- 充值库存 -->
    <a-modal
      v-model:visible="comStockVisible1"
      @before-close="handleCancelComStock1"
      title="支付订单"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="comStockRef1" :auto-label-width="true" :model="stockInfo1">
        <a-form-item
          label="支付类型"
          field="payType"
          :rules="[{ required: true, message: '支付类型不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-radio-group
            @change="getPay(stockInfo1.type)"
            class="radio-bcg"
            v-model="stockInfo1.type"
          >
            <a-radio :value="5"
              ><template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">库存</div>
                </div>
              </template></a-radio
            >
            <a-radio :value="0"
              ><template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">余额</div>
                </div>
              </template></a-radio
            >
            <a-radio v-for="(item, index) in typeList" :key="index" :value="index + 1">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">{{ item.name }}</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          field="payId"
          v-if="stockInfo1.payList.length > 1 && stockInfo1.type !== 0 && stockInfo1.type !== 5"
          label="支付商户"
        >
          <a-select
            placeholder="请选择支付商户"
            allow-search
            v-model="stockInfo1.payId"
            @change="getPayFn(stockInfo1.payId)"
          >
            <a-option v-for="item in stockInfo1.payList" :key="item.id" :value="item.id">{{
              item.name
            }}</a-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="handleCancelComStock1">取消</a-button>
          <a-button :loading="loading" type="primary" @click="handleBeforeComStock1">确定</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { formpost, get, post } from '@/api/http'
  import { usePagination, useRowKey, useTable } from '@/hooks/table'
  import { computed, onMounted, reactive, ref } from 'vue'
  import useCommonStore from '@/store/modules/common'
  import { Message, Modal } from '@arco-design/web-vue'
  import { qr } from '@/api/url'
  let other = window.location.protocol + '//' + window.location.host
  const useCommon = useCommonStore()
  const index = ref(0)
  function numberFn(val: any) {
    index.value = val
  }
  function openPay() {
    stockInfo1.value.type = 5
    if (putList.value.length > 0) {
      getPay(1)
      comStockVisible1.value = true
    } else {
    }
  }
  function onCardSuccess1(fileItem: any) {
    updateForm.value.photoFullFace = fileItem.response.data.path
    updateForm.value.photoFullFaces = fileItem.url
  }
  function onCardSuccess2(fileItem: any) {
    updateForm.value.photoReverseSide = fileItem.response.data.path
    updateForm.value.photoReverseSides = fileItem.url
  }
  function onCardSuccess3(fileItem: any) {
    updateForm.value.photoBareheaded = fileItem.response.data.path
    updateForm.value.photoBareheadeds = fileItem.url
  }
  function onError(fileItem: any) {
    Message.error(fileItem.response.msg)
  }
  //获取邮费
  function getFee(val: any, code: any) {
    const list: any = []
    val.forEach((item: any) => {
      if (item.number > 0) {
        list.push(item.id)
      }
    })
    const codes = useCommon.getCityCodeByDistrictCode(code, districtsList.value)
    if (list.length > 0) {
      get({
        url: '/app/mall/order/get/post/fee',
        data: {
          mallIds: list, //              订单ID
          areaCode: codes, //       收件人姓名
        },
      }).then((res) => {
        if (res.code == 0) {
          putList.value[index.value].expressFee = res.data
          putList.value[index.value].total = total.value + res.data
          putList.value[index.value].totalCost = totalCost.value
          putList.value[index.value].totalNumber = totalNumber.value
          putList.value[index.value].totalPrice = totalPrice.value
          updateTotalTop()
          everyGoodFn()
          // return res.data
        }
      })
      // return 10
    } else {
      putList.value[index.value].expressFee = 0
      putList.value[index.value].total = total.value
      putList.value[index.value].totalCost = totalCost.value
      putList.value[index.value].totalNumber = totalNumber.value
      putList.value[index.value].totalPrice = totalPrice.value
      updateTotalTop()
      everyGoodFn()
    }
  }
  //下单
  const comStockVisible1 = ref(false)
  const loading = ref(false)
  const comStockRef1 = ref()
  const stockInfo1 = ref({
    type: 3,
    payId: '',
    state: '',
    payList: [],
  })
  const getPayFn = (val: any) => {
    path.value = ''
    stockInfo1.value.payList.forEach((item: any) => {
      if (item.id == val) {
        stockInfo1.value.payId = val
        // detailForm.price = Math.floor((detailForm.name * item.serviceCharge * 100) / 100) / 100
        if (item.payProduct.type == 2) {
          if (item.payProduct.path) {
            if (uid.value == '') {
              uid.value = guid2()
            }
            path.value = `${window.location.protocol}//${window.location.host}${item.payProduct.path}?payId=${val}&state=${uid.value}&redirectUri=${window.location.protocol}//${window.location.host}/web/template/wechat/login/success`
          }
        }
      }
    })
  }
  function handleCancelComStock1() {
    comStockVisible1.value = false
  }
  function paySuccessFnX() {
    const list = JSON.parse(JSON.stringify(putList.value))
    list.forEach((item: any) => {
      // 初始化 phoneParams
      item.phoneParams = {}
      // 过滤掉 number 为 0 的 mallOrderItems 元素
      item.mallOrderItems = item.mallOrderItems.filter((itemq: any) => itemq.number !== 0)
      // 设置 type 和初始化 orders 数组
      item.type = stockInfo1.value.type
      item.orders = []
      // 遍历 mallOrderItems 并填充 orders 数组
      item.mallOrderItems.forEach((itemq: any) => {
        item.orders.push({ mallId: itemq.id, number: itemq.number })
      })
      // 用 orders 数组替换 mallOrderItems
      item.mallOrderItems = item.orders
      // 删除不再需要的 orders 属性
      delete item.orders
    })
    loadings.value = true
    post({
      url:
        '/app/mall/order/user/backstage/pay?payId=' +
        stockInfo1.value.payId +
        '&state=' +
        uid.value,
      data: list,
    })
      .then((res) => {
        if (res.code == 0) {
          loadings.value = false
          if (uid.value == '') {
            visibleX.value = false
            Message.success(res.msg)
          } else {
            loadings.value = false
            if (res.data.qrcode && res.data.openUrl) {
              if (is_weixn() == false) {
                imgUrl.value = `${window.location.protocol}//${
                  window.location.host
                }${qr}?content=${encodeURIComponent(res.data.qrcode)}`
                path.value = ''
                visibleX.value = true
              } else {
                // let a = document.createElement('a')
                // a.setAttribute('href', res.data.openUrl)
                // a.setAttribute('target', '_blank')
                // document.body.appendChild(a)
                // a.click()
                // a.remove()
                if (isIOS() == true) {
                  window.location.href = res.data.openUrl
                } else {
                  window.open(res.data.openUrl)
                }
              }
            } else {
              if (res.data.qrcode) {
                imgUrl.value = `${window.location.protocol}//${
                  window.location.host
                }${qr}?content=${encodeURIComponent(res.data.qrcode)}`
                path.value = ''
                visibleX.value = true
              } else {
                // let a = document.createElement('a')
                // a.setAttribute('href', res.data.openUrl)
                // a.setAttribute('target', '_blank')
                // document.body.appendChild(a)
                // a.click()
                // a.remove()
                if (isIOS() == true) {
                  window.location.href = res.data.openUrl
                } else {
                  window.open(res.data.openUrl)
                }
              }
            }
          }
        }
      })
      .catch(() => {
        loadings.value = false
      })
  }
  function handleBeforeComStock1() {
    const list = JSON.parse(JSON.stringify(putList.value))
    list.forEach((item: any) => {
      // 初始化 phoneParams
      item.phoneParams = {}
      // 过滤掉 number 为 0 的 mallOrderItems 元素
      item.mallOrderItems = item.mallOrderItems.filter((itemq: any) => itemq.number !== 0)
      // 设置 type 和初始化 orders 数组
      item.type = stockInfo1.value.type
      item.orders = []
      // 遍历 mallOrderItems 并填充 orders 数组
      item.mallOrderItems.forEach((itemq: any) => {
        item.orders.push({ mallId: itemq.id, number: itemq.number })
      })
      // 用 orders 数组替换 mallOrderItems
      item.mallOrderItems = item.orders
      // 删除不再需要的 orders 属性
      delete item.orders
    })
    if (stockInfo1.value.type == 0 || stockInfo1.value.type == 5) {
      post({
        url: '/app/mall/order/user/stock/pay?type=' + stockInfo1.value.type,
        data: list,
      }).then((res) => {
        if (res.code == 0) {
          Message.success(res.msg)
          handleCancelComStock1()
          putList.value = []
          allGoodList.value = []
          generalStock()
          doRefresh()
        }
      })
    } else {
      if (path.value != '') {
        imgUrl.value = `${window.location.protocol}//${
          window.location.host
        }${qr}?content=${encodeURIComponent(path.value)}`
        visibleX.value = true
      } else {
        post({
          url:
            '/app/mall/order/user/backstage/pay?payId=' +
            stockInfo1.value.payId +
            '&state=' +
            uid.value,
          data: list,
        }).then((res) => {
          if (res.code == 0) {
            // seachForm.value.payForm = res.data
            if (res.data.qrcode && res.data.openUrl) {
              if (is_weixn() == false) {
                imgUrl.value = `${window.location.protocol}//${
                  window.location.host
                }${qr}?content=${encodeURIComponent(res.data.qrcode)}`
                path.value = ''
                visibleX.value = true
              } else {
                // let a = document.createElement('a')
                // a.setAttribute('href', res.data.openUrl)
                // a.setAttribute('target', '_blank')
                // document.body.appendChild(a)
                // a.click()
                // a.remove()
                if (isIOS() == true) {
                  window.location.href = res.data.openUrl
                } else {
                  window.open(res.data.openUrl)
                }
              }
            } else {
              if (res.data.qrcode) {
                imgUrl.value = `${window.location.protocol}//${
                  window.location.host
                }${qr}?content=${encodeURIComponent(res.data.qrcode)}`
                path.value = ''
                visibleX.value = true
              } else {
                // let a = document.createElement('a')
                // a.setAttribute('href', res.data.openUrl)
                // a.setAttribute('target', '_blank')
                // document.body.appendChild(a)
                // a.click()
                // a.remove()
                if (isIOS() == true) {
                  window.location.href = res.data.openUrl
                } else {
                  window.open(res.data.openUrl)
                }
              }
            }
          }
        })
      }
    }
  }
  //支付
  const visibleX = ref(false)
  const loadings = ref(false)
  const imgUrl = ref('')
  const uid = ref('')
  const path = ref('')
  const typeList: any = ref([])
  const beforCloseX = () => {
    generalStock()
    doRefresh()
    visibleX.value = false
  }
  function isIOS() {
    const userAgent = navigator.userAgent.toLowerCase()
    return /iphone|ipad|ipod/.test(userAgent)
  }
  function is_weixn() {
    var ua: any = navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      return true
    } else {
      return false
    }
  }
  function guid2() {
    function S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    }
    return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4()
  }
  const getPay = (val: any) => {
    if (val != 0 && val != 5) {
      stockInfo1.value.payId = ''
      uid.value = ''
      path.value = ''
      useCommon.getPayList(val).then((res: any) => {
        typeList.value = res.data
        stockInfo1.value.payList = res.data[val - 1].list
        stockInfo1.value.payId = res.data[val - 1].list[0].id

        if (res.data[val - 1].list[0].payProduct.type == 2) {
          if (res.data[val - 1].list[0].payProduct.path) {
            uid.value = guid2()
            console.log(uid.value)
            path.value = `${window.location.protocol}//${window.location.host}${
              res.data[val - 1].list[0].payProduct.path
            }?payId=${stockInfo1.value.payId}&state=${uid.value}&redirectUri=${
              window.location.protocol
            }//${window.location.host}/web/template/wechat/login/success`
          }
        }
      })
    } else {
      stockInfo1.value.payList = []
    }
  }
  //计算每个商品的总数量
  function everyGoodFn() {
    const list: number[] = new Array(allGoodList.value.length).fill(0)
    // 遍历 putList.value 及其内部的 mallOrderItems，累加对应位置的 number 值到 list 中
    putList.value.forEach((items: any) => {
      items.mallOrderItems.forEach((itemq: any, index: number) => {
        list[index] += itemq.number
      })
    })
    // 直接根据索引将 list 中的值赋给 allGoodList.value 对应元素的 number 属性
    allGoodList.value.forEach((item: any, index: number) => {
      item.number = list[index]
    })
  }
  // 计算总金额
  const totalTop = computed(() => {
    return putList.value.reduce((acc: any, product: any) => {
      return acc + product.total
    }, 0)
  })
  // 计算商品成本
  const totalCostTop = computed(() => {
    return putList.value.reduce((acc: any, product: any) => {
      return acc + product.totalCost
    }, 0)
  })
  // 计算下单数量
  const totalNumberTop = computed(() => {
    return putList.value.reduce((acc: any, product: any) => {
      return acc + product.totalNumber
    }, 0)
  })
  // 计算下单金额
  const totalPriceTop = computed(() => {
    return putList.value.reduce((acc: any, product: any) => {
      return acc + product.totalPrice
    }, 0)
  })
  // 计算下单邮费
  const totalFeeTop = computed(() => {
    return putList.value.reduce((acc: any, product: any) => {
      return acc + product.expressFee
    }, 0)
  })
  // 更新总金额的方法
  const updateTotalTop = () => {
    // putList.value[index.value].expressFee = getFee(
    //   putList.value[index.value].mallOrderItems,
    //   putList.value[index.value].regionalCode
    // )
    totalTop.value
    totalCostTop.value
    totalNumberTop.value
    totalPriceTop.value
    totalFeeTop.value
  }
  //删除商品
  function delGoodFn(val: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要删除此商品吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '删除',
      onOk: () => {
        if (putList.value.length > 0) {
          if (allGoodList.value.length > 1) {
            const valId = val.id
            // 先找出需要删除元素在 allGoodList.value 中的索引
            const indexInAllGoodList = allGoodList.value.findIndex(
              (element: any) => element.id === valId
            )
            if (indexInAllGoodList !== -1) {
              // 使用 filter 方法创建新数组，过滤掉要删除的元素，避免直接使用 splice 改变原数组长度和索引导致的问题
              allGoodList.value = allGoodList.value.filter((element: any) => element.id !== valId)

              // 遍历 putList.value 及其内部的 mallOrderItems，同样使用 filter 方法过滤掉对应要删除的元素
              putList.value = putList.value.map((element: any) => {
                element.mallOrderItems = element.mallOrderItems.filter(
                  (item: any) => item.id !== valId
                )
                return element
              })

              // 统一更新 putList.value 中各元素的相关属性
              putList.value.forEach((element: any) => {
                element.total = total.value
                element.totalCost = totalCost.value
                element.totalNumber = totalNumber.value
                element.totalPrice = totalPrice.value
              })

              updateTotalTop()
            }
          } else {
            Message.error('已有收货详情，必须保留一个上商品')
          }
        } else {
          const indexInAllGoodList = allGoodList.value.findIndex(
            (element: any) => element.id === val.id
          )
          if (indexInAllGoodList !== -1) {
            allGoodList.value = allGoodList.value.filter((element: any) => element.id !== val.id)
          }
        }
      },
    })
  }
  // 更新总金额的方法
  const updateTotal = () => {
    getFee(putList.value[index.value].mallOrderItems, putList.value[index.value].regionalCode)
    // setInterval(() => {
    //   putList.value[index.value].total = total.value
    //   putList.value[index.value].totalCost = totalCost.value
    //   putList.value[index.value].totalNumber = totalNumber.value
    //   putList.value[index.value].totalPrice = totalPrice.value
    //   updateTotalTop()
    //   everyGoodFn()
    // }, 1000)
  }
  // 计算总金额
  const total = computed(() => {
    console.log(putList.value[index.value])
    return putList.value[index.value].mallOrderItems.reduce((acc: any, product: any) => {
      console.log(acc)
      return acc + product.cost * product.number
    }, 0)
  })
  // 计算商品成本
  const totalCost = computed(() => {
    return putList.value[index.value].mallOrderItems.reduce((acc: any, product: any) => {
      return acc + product.cost
    }, 0)
  })
  // 计算下单数量
  const totalNumber = computed(() => {
    return putList.value[index.value].mallOrderItems.reduce((acc: any, product: any) => {
      return acc + product.number
    }, 0)
  })
  // 计算下单金额
  const totalPrice = computed(() => {
    return putList.value[index.value].mallOrderItems.reduce((acc: any, product: any) => {
      return acc + product.number * product.cost
    }, 0)
  })
  //通用库存
  const generalInventory = ref(0)
  //下单信息
  const updateVisible = ref(false)
  const updateForm: any = ref({
    senderId: '',
    userRemarks: '',
    divideCustomersId: '',
    /**
     * 收件人姓名
     */
    expressName: '',
    /**
     * 收件人手机号
     */
    expressPhone: '',
    /**
     * 收件人身份证
     */
    expressIdCard: '',
    /**
     * 收件地区code
     */
    regionalCode: '',
    /**
     * 收货地址
     */
    expressAddress: '',
    /**
     * 下单备注
     */
    placeOrderRemark: '',
    //选号
    recipientNumber: '',
    phoneParams: {},
    type: 5,
    number: 1,
    expressFee: 0,
    idState: false,
    payId: '',
    payList: [],
  })
  const updateRef = ref()
  const districtsList: any = ref([])
  const fieldNames = { value: 'code', label: 'name' }
  function changeCode(val: any) {
    const list: any = []
    allGoodList.value.forEach((item: any) => {
      list.push(item.id)
    })
    const code = useCommon.getCityCodeByDistrictCode(val, districtsList.value)
    get({
      url: '/app/mall/order/get/post/fee',
      data: {
        mallIds: list, //              订单ID
        areaCode: code, //       收件人姓名
      },
    }).then((res) => {
      if (res.code == 0) {
        updateForm.value.expressFee = res.data
      }
    })
  }
  //智能识别
  function intellectIdentifyFn() {
    get({
      url: '/app/address/parser',
      data: {
        str: updateForm.value.str,
      },
    }).then((res) => {
      if (res.code == 0) {
        if (res.data.name) {
          updateForm.value.expressName = res.data.name
        }
        if (res.data.phone) {
          updateForm.value.expressPhone = res.data.phone
        }
        if (res.data.detailAddress) {
          updateForm.value.expressAddress = res.data.detailAddress
        }

        const { districtCode, cityCode, provinceCode } = res.data
        const validAddress = districtCode ?? cityCode ?? provinceCode ?? ''
        updateForm.value.regionalCode = validAddress
        console.log(validAddress)
        updateForm.value.address = useCommon.getAreaNamesByCode(validAddress, districtsList.value)
        console.log(useCommon.getAreaNamesByCode(validAddress, districtsList.value))
      }
    })
  }
  function delPutFn(val: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要删除此收货详情吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '删除',
      onOk: () => {
        const index = putList.value.findIndex((element: any) => element.id === val.id)
        putList.value.splice(index, 1)
        everyGoodFn()
      },
    })
  }
  function openUpdate(val?: any) {
    if (allGoodList.value.length > 0) {
      sendUserListFn()
      useCommon.getDistrictsList(3).then((res: any) => {
        districtsList.value = res.data
      })
      getUserList()
      const obj = allGoodList.value.find((element: any) => element.idCard !== 0)
      const objs = allGoodList.value.find((element: any) => element.idCardImg == true)

      if (val) {
        updateForm.value = JSON.parse(JSON.stringify(val))
      }
      if (obj) {
        updateForm.value.idState = 1
      } else {
        updateForm.value.idState = 0
      }
      if (objs) {
        updateForm.value.idCardImg = true
      } else {
        updateForm.value.idCardImg = false
      }
      updateVisible.value = true
    } else {
      Message.error('请先选择商品')
    }
  }
  function beforeCloseUpdate() {
    updateForm.value.id = null
    updateRef.value.resetFields()
    updateRef.value.clearValidate()
    updateVisible.value = false
  }
  const id = ref(0)
  function confirmUpdate() {
    updateRef.value.validate((error: any) => {
      if (!error) {
        if (updateForm.value.id) {
          const index = putList.value.findIndex(
            (element: any) => element.id === updateForm.value.id
          )
          getFee(updateForm.value.mallOrderItems, updateForm.value.regionalCode)
          updateForm.value.address = useCommon.getAreaNamesByCode(
            updateForm.value.regionalCode,
            districtsList.value
          )
          putList.value[index] = JSON.parse(JSON.stringify(updateForm.value))
        } else {
          index.value = putList.value.length
          updateForm.value.address = useCommon.getAreaNamesByCode(
            updateForm.value.regionalCode,
            districtsList.value
          )
          const mallOrderItems: any[] = allGoodList.value.map((item: any) => ({
            ...item,
            number: 0,
          }))
          putList.value.push({
            ...updateForm.value,
            id: id.value++,
            mallOrderItems: mallOrderItems,
          })
          updateTotal()
          putList.value[index.value].total = total.value
          putList.value[index.value].totalCost = totalCost.value
          putList.value[index.value].totalNumber = totalNumber.value
          putList.value[index.value].totalPrice = totalPrice.value

          // beforeCloseUpdate()
        }
        beforeCloseUpdate()
        updateTotalTop()
      }
    })
  }
  //客户
  const userLists = ref([])
  function getUserList() {
    useCommon.userListse().then((res: any) => {
      userLists.value = res.data
    })
  }
  //下单列表
  const putList: any = ref([])
  //统计商品列表
  const allGoodList: any = ref([])
  //点击商品添加下单数据
  function handleRowClick(record: any) {
    record.number = 0
    record.mallId = record.id
    // 获取行的下标
    if (allGoodList.value.length > 0) {
      const obj = allGoodList.value.find((element: any) => element.id === record.id)
      if (!obj) {
        allGoodList.value.push(record)
        if (putList.value.length > 0) {
          putList.value.forEach((item: any) => {
            item.mallOrderItems.push(record)
          })
        }
      }
    } else {
      allGoodList.value.push(record)
    }
  }
  //下单商品列表
  const putGoodColumns = ref([
    {
      title: '商品名称',
      key: 'name',
      dataIndex: 'name',
      checked: true,
      width: 400,
    },
    {
      title: '商品成本',
      key: 'cost',
      dataIndex: 'cost',
      checked: true,
      width: 180,
    },
    {
      title: '下单数量',
      key: 'number',
      dataIndex: 'number',
      checked: true,
      width: 180,
    },
    {
      title: '下单金额',
      key: 'allPrice',
      dataIndex: 'allPrice',
      checked: true,
      width: 180,
    },
  ])
  //统计列表
  const allGoodColumns = ref([
    {
      title: '商品名称',
      key: 'name',
      dataIndex: 'name',
      checked: true,
      width: 400,
    },
    {
      title: '商品成本',
      key: 'cost',
      dataIndex: 'cost',
      checked: true,
      width: 180,
    },
    {
      title: '我的库存',
      key: 'mallMallStock',
      dataIndex: 'mallMallStock',
      checked: true,
      width: 180,
    },
    {
      title: '下单数量',
      key: 'number',
      dataIndex: 'number',
      checked: true,
      width: 180,
    },
    {
      title: '下单金额',
      key: 'allPrice',
      dataIndex: 'allPrice',
      checked: true,
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      dataIndex: 'action',
      checked: true,
      width: 80,
    },
  ])
  // 商品列表
  const pagination = usePagination(doRefresh)
  const rowKey = useRowKey('id')
  const userTableList = ref([
    {
      title: '商品名称',
      key: 'name',
      dataIndex: 'name',
      checked: true,
      width: 150,
    },
    {
      title: '库存',
      key: 'mallMallStock',
      dataIndex: 'mallMallStock',
      checked: true,
      width: 130,
    },
  ])
  const table = useTable()
  const tables = reactive({
    tableLoading: false,
  })
  //商品列表搜索项
  const form = reactive({
    mallId: '',
    name: '',
    state: '',
    addTime: '',
    endTime: '',
    addPrice: '',
    endPrice: '',
    classId: '',
  })
  function doRefresh(value?: number) {
    tables.tableLoading = true
    if (value) {
      pagination.page = value
    }
    formpost({
      url: '/app/mall/user/get/mall/list',
      data: () => {
        return {
          page: pagination.page,
          size: pagination.pageSize,
          ...form,
        }
      },
    }).then((res: any) => {
      tables.tableLoading = false
      table.handleSuccess(res.data.list)
      pagination.setTotalSize((res.data as any).totalSize)
    })
  }
  function generalStock() {
    get({
      url: '/app/mall/general/stock/user/get',
    }).then((res: any) => {
      console.log(res)
      generalInventory.value = res.data.generalStock
    })
  }
  const sendUserList: any = ref([])
  function sendUserListFn() {
    get({
      url: '/app/mall/sender/user/get/list',
    }).then((res: any) => {
      sendUserList.value = res.data
    })
  }
  onMounted(() => {
    pagination.showSizePicker = false
    doRefresh()
    generalStock()
  })
</script>

<style lang="less" scoped>
  .all-box {
    background-color: var(--color-bg-1);
    border-radius: 10px;
    height: calc(100vh - 145px);
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;
    .box-left {
      width: 20%;
      border-right: 1px solid var(--color-neutral-2);
      padding: 20px;
      .tong {
        width: 100%;
        border-radius: 5px;
        margin-top: 20px;
        line-height: 32px;
        padding-left: 12px;
        font-size: 12px;
        color: #3491fa;
        background-color: #f2f3f5;
      }
    }
    .box-right {
      padding: 20px;
      width: 80%;
      .top-but {
        display: flex;
        width: 100%;
        .top-left {
          width: calc(100% - 88px);
          border: 1px solid #3491fa;
          line-height: 32px;
          border-radius: 5px;
          padding-left: 12px;
        }
      }
      .putTitle {
        font-size: 16px;
        margin-top: 20px;
      }
      .putList {
        // background: #3491fa;
        height: calc(100vh - 450px);
        overflow: hidden;
        overflow-y: scroll;
        .item {
          .item-top {
            margin-top: 20px;
            background-color: #f2f3f5;
            line-height: 35px;
            border-radius: 5px;
            padding-left: 12px;
            font-size: 13px;
            display: flex;
            justify-content: space-between;
          }
        }
      }
    }
  }
</style>
